const express = require('express');
const router = express.Router();
const weatherService = require('../services/weatherService');

/**
 * 通过IP获取当前城市天气
 * GET /api/weather
 */
router.get('/', async (req, res) => {
  try {
    const clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress || '';
    const ip = clientIp.split(',')[0].trim();
    
    const weatherData = await weatherService.getWeatherByIP(ip);
    
    res.json({
      success: true,
      data: weatherData
    });
  } catch (error) {
    console.error('获取天气数据失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取天气数据失败，请稍后重试'
    });
  }
});

/**
 * 根据城市编码获取天气
 * GET /api/weather/city/:cityCode
 */
router.get('/city/:cityCode', async (req, res) => {
  try {
    const { cityCode } = req.params;
    
    if (!cityCode) {
      return res.status(400).json({
        success: false,
        message: '城市编码不能为空'
      });
    }
    
    const weatherData = await weatherService.getCachedWeatherData(cityCode);
    
    res.json({
      success: true,
      data: weatherData
    });
  } catch (error) {
    console.error('获取天气数据失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取天气数据失败'
    });
  }
});

/**
 * 搜索城市
 * GET /api/weather/search
 */
router.get('/search', async (req, res) => {
  try {
    const { keyword } = req.query;
    
    if (!keyword) {
      return res.status(400).json({
        success: false,
        message: '搜索关键词不能为空'
      });
    }
    
    const cities = await weatherService.searchCity(keyword);
    
    res.json({
      success: true,
      data: cities
    });
  } catch (error) {
    console.error('城市搜索失败:', error);
    res.status(500).json({
      success: false,
      message: '城市搜索失败，请稍后重试'
    });
  }
});

/**
 * 获取完整天气数据（包含推荐信息）
 * GET /api/weather/complete/:cityCode
 */
router.get('/complete/:cityCode', async (req, res) => {
  try {
    const { cityCode } = req.params;
    
    const weatherData = await weatherService.getCompleteWeatherData(cityCode);
    
    res.json({
      success: true,
      data: weatherData
    });
  } catch (error) {
    console.error('获取完整天气数据失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取天气数据失败'
    });
  }
});

/**
 * 获取天气推荐文案
 * GET /api/weather/recommendation
 */
router.get('/recommendation', async (req, res) => {
  try {
    const { weatherCondition, temperature } = req.query;
    
    if (!weatherCondition || !temperature) {
      return res.status(400).json({
        success: false,
        message: '缺少天气参数'
      });
    }
    
    const recommendationText = weatherService.getWeatherRecommendationText(
      weatherCondition,
      parseFloat(temperature)
    );
    
    res.json({
      success: true,
      data: {
        text: recommendationText,
        weatherCondition,
        temperature: parseFloat(temperature)
      }
    });
  } catch (error) {
    console.error('获取推荐文案失败:', error);
    res.status(500).json({
      success: false,
      message: '获取推荐文案失败'
    });
  }
});

/**
 * 获取天气图标类型
 * GET /api/weather/icon-type
 */
router.get('/icon-type', async (req, res) => {
  try {
    const { weather } = req.query;
    
    if (!weather) {
      return res.status(400).json({
        success: false,
        message: '天气描述不能为空'
      });
    }
    
    const iconType = weatherService.getWeatherIconType(weather);
    
    res.json({
      success: true,
      data: {
        iconType,
        weather
      }
    });
  } catch (error) {
    console.error('获取图标类型失败:', error);
    res.status(500).json({
      success: false,
      message: '获取图标类型失败'
    });
  }
});

module.exports = router;